﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace AuthorityCenterCore
{
    /// <summary>
    /// http全局错误处理 使用方式 services.AddControllers(options =>options.Filters.Add(new HttpResponseExceptionFilter()));
    /// </summary>
    #region snippet_HttpResponseExceptionFilter
    public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpResponseExceptionFilter()
        {
        }
        /// <summary>
        /// 优先级
        /// </summary>
        public int Order { get; set; } = int.MaxValue - 10;
        /// <summary>
        /// 执行中
        /// </summary>
        /// <param name="context">上下文对象</param>
        public void OnActionExecuting(ActionExecutingContext context) { }
        /// <summary>
        /// 执行完成
        /// </summary>
        /// <param name="context">上下文对象</param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            Exception ex = context.Exception;
            if (ex != null)
            {
                LoggerFact.Logger.GetLogger.Fatal(ex);
                context.Result = new JsonResult(ex.Message);
                context.ExceptionHandled = true;
            }
        }
    }
    #endregion
}
